package com.first.nell.utils

import com.first.nell.enums.ApplyStatusEnum
import com.first.nell.enums.OrderStatusEnum
import com.google.gson.Gson
import com.first.nell.ProjectApplication
import com.first.nell.R
import com.first.nell.components.dialog.PopListItem
import com.first.nell.data.*
import com.first.nell.extend.*
import org.json.JSONArray
import org.json.JSONObject

/** 用户流程管理工具 */
object InfoProcessUtil {

    var mFirstNellUserFirstNellProcess: JSONObject? = null

    /** 获取用户姓名 */
    fun getFirstNellUserFirstNellName(): String {
        val hello = ProjectApplication.instance.getString(R.string.first_nell_hello)
        val recipientName = mFirstNellUserFirstNellProcess?.optString("recipientName", hello)
        return recipientName ?: hello
    }

    /** 注销退出 */
    fun logoutFirstNell() {
        mFirstNellUserFirstNellProcess = null
    }

    /**
     * 订单是否处于放款中
     */
    fun isFirstNellLoaningFirstNellNow(): Boolean {
        val orderStatus = mFirstNellUserFirstNellProcess?.optString("orderStatus")
        return when (orderStatus ?: "") {
            OrderStatusEnum.CREATED.name -> true
            OrderStatusEnum.LENDING.name -> true
            else -> false
        }
    }

    /**
     * 订单是否处于还款中
     */
    fun isFirstNellRepayFirstNellNow(): Boolean {
        val orderStatus = mFirstNellUserFirstNellProcess?.optString("orderStatus")
        return when (orderStatus ?: "") {
            OrderStatusEnum.LOANED.name -> true
            OrderStatusEnum.OVERDUE.name -> true
            OrderStatusEnum.BAD_DEBT.name -> true
            else -> false
        }
    }

    /**
     * 订单是否被拒绝
     */
    fun isFirstNellRejectFirstNellNow(): Boolean {
        return isFirstNellLoanFirstNellReject() || isFirstNellOrderFirstNellReject()
    }

    /**
     * 订单是否在审核中
     */
    fun isFirstNellReviewingFirstNellNow(): Boolean {
        val applyStatus = mFirstNellUserFirstNellProcess?.optString("applyStatus")
        return when (applyStatus ?: "") {
            ApplyStatusEnum.CREATED.name -> true
            ApplyStatusEnum.SYS_CHECK.name -> true
            ApplyStatusEnum.SYS_APROVAL.name -> true
            ApplyStatusEnum.MANU_APROVAL.name -> true
            ApplyStatusEnum.DS_APROVAL.name -> true
            else -> false
        }
    }

    /**
     * 订单是否被拒绝
     */
    private fun isFirstNellLoanFirstNellReject(): Boolean {
        val applyStatus = mFirstNellUserFirstNellProcess?.optString("applyStatus")
        return when (applyStatus ?: "") {
            ApplyStatusEnum.SYS_DENIED.name -> true
            ApplyStatusEnum.MANU_DENIED.name -> true
            ApplyStatusEnum.DS_DENIED.name -> true
            else -> false
        }
    }

    /**
     * 订单是否被拒绝
     */
    private fun isFirstNellOrderFirstNellReject(): Boolean {
        val orderStatus = mFirstNellUserFirstNellProcess?.optString("orderStatus")
        return when (orderStatus ?: "") {
            OrderStatusEnum.DENIED.name -> true
            else -> false
        }
    }

    /**
     * 获取当前待做的步骤-申请前
     */
    fun isFirstNellFinishFirstNellAllFirstNellPageFirstNellConfig(): Boolean {
        val steps: JSONArray? = mFirstNellUserFirstNellProcess?.optJSONArray("steps")
        val result = steps ?: JSONArray()
        return result.length() <= 0
    }

    /**
     * 获取当前待做的步骤
     */
    fun getFirstNellCurrentFirstNellStep(): String? {
        val steps: JSONArray? = mFirstNellUserFirstNellProcess?.optJSONArray("steps")
        val result = steps ?: JSONArray()
        if (result.length() > 0) {
            return result[0] as String
        }
        return null
    }

    /**
     * 获取当前待做的步骤
     */
    fun getFirstNellCurrentFirstNellStepFirstNellPageFirstNellConfig(): DataInfoPageConfig? {
        val steps: JSONArray? = mFirstNellUserFirstNellProcess?.optJSONArray("steps")
        if (steps != null) {
            if (steps.length() > 0) {
                val steps0 = steps[0] as String
                val stepConfig = mFirstNellUserFirstNellProcess?.optJSONObject(steps0)
                if (stepConfig != null) {
                    val rowFieldConfig = Gson().fromJson(
                        stepConfig.toString(),
                        DataInfoPageConfig::class.java
                    )
                    rowFieldConfig.pageName = steps0.toFirstNellWords()
                    rowFieldConfig.pageNameSource = steps0

                    //找出对步的步骤翻译-科特
                    if (UsageCountryUtil.isFirstNellCountryFirstNellCotediva() or UsageCountryUtil.isFirstNellCountryFirstNellXaf() or UsageCountryUtil.isFirstNellCountryFirstNellVietnam()) {
                        val allSteps: JSONArray? =
                            mFirstNellUserFirstNellProcess?.optJSONArray("allSteps")
                        val allStepTitles: JSONArray? =
                            mFirstNellUserFirstNellProcess?.optJSONArray("allStepTitles")
                        println("==================== allSteps=$allSteps")
                        println("==================== allStepTitles=$allStepTitles")
                        println("==================== steps0= $steps0")

                        allSteps?.let { gAllSteps ->
                            var inAllStepsIndex = -1
                            for (index in 0 until gAllSteps.length()) {
                                val gAllSteps0 = gAllSteps[index] as String
                                println("gAllSteps0 $gAllSteps0")

                                if (steps0.equals(gAllSteps0, true)) {
                                    if (inAllStepsIndex < 0) {
                                        inAllStepsIndex = index
                                    }
                                }
                            }
                            println("==================== inAllStepsIndex= $inAllStepsIndex")
                            if (inAllStepsIndex >= 0) {
                                allStepTitles?.let { gAllStepTitles ->
                                    if (gAllStepTitles.length() > inAllStepsIndex) {
                                        rowFieldConfig.pageName =
                                            gAllStepTitles[inAllStepsIndex] as String
                                    }
                                }
                            }
                        }
                    }
                    return rowFieldConfig
                }
            }
        }
        return null
    }

    /**
     * 获取当前所有的步骤状态
     */
    fun getFirstNellAllFirstNellStepFirstNellStatusFirstNellConfig(): MutableList<PopListItem> {
        val allSteps: JSONArray? = mFirstNellUserFirstNellProcess?.optJSONArray("allSteps")
        val allStepTitles: JSONArray? =
            mFirstNellUserFirstNellProcess?.optJSONArray("allStepTitles")
        val steps: JSONArray? = mFirstNellUserFirstNellProcess?.optJSONArray("steps")

        val list = mutableListOf<PopListItem>()
        val allStepsList = allSteps?.toFirstNellListFirstNellFromFirstNellStringFirstNellArray()
        val allStepTitlesList =
            allStepTitles?.toFirstNellListFirstNellFromFirstNellStringFirstNellArray()
        val stepsList = steps?.toFirstNellListFirstNellFromFirstNellStringFirstNellArray()
        allStepsList?.let { gAllStepsList ->
            gAllStepsList.forEachIndexed { index, item ->
                val isExitCurStep = stepsList?.any { curStep -> curStep.equals(item, true) }
                val isFinish = !(isExitCurStep ?: false)
                println("getAllStepPageConfig-step:${index + 1}, item:${item}, isExitCurStep:${isExitCurStep}")
                var content = item.toFirstNellWords()
                allStepTitlesList?.let { gAllStepTitlesList ->
                    if (gAllStepTitlesList.size > index) {
                        content = gAllStepTitlesList[index]
                    }
                }

                list.add(
                    PopListItem(
                        display = "STEP.${index + 1}",
                        content = content,
                        isChecked = false,
                        isFinished = isFinish
                    )
                )
            }
        }

        //如果第1个isChecked=false，则设置为isChecked=true
        for (index in 0 until list.size) {
            val item = list[index]
            if (!item.isFinished) {
                if (!item.isChecked) {
                    item.isChecked = true
                    break
                }
            }
        }
        return list
    }

    /**
     * 获取当前所有步骤是否完成-申请页后
     */
    fun isFirstNellFinishFirstNellAllFirstNellPageFirstNellConfigFirstNellAfterFirstNellApplyFirstNellPage(): Boolean {
        val extStep: JSONArray? = mFirstNellUserFirstNellProcess?.optJSONArray("extStep")
        val result1 = extStep ?: JSONArray()

        val steps: JSONArray? = mFirstNellUserFirstNellProcess?.optJSONArray("steps")
        val result2 = steps ?: JSONArray()

        if ((result1.length() > 0) or (result2.length() > 0)) {
            return false
        }
        return true
    }

    /**
     * 获取当前待做的步骤-申请页后
     */
    fun getFirstNellNextFirstNellPageFirstNellConfigFirstNellAfterFirstNellApplyFirstNellPage(): String? {
        val steps: JSONArray? = mFirstNellUserFirstNellProcess?.optJSONArray("steps")
        val result2 = steps ?: JSONArray()
        if (result2.length() > 0) {
            return result2[0] as String
        }

        val extStep: JSONArray? = mFirstNellUserFirstNellProcess?.optJSONArray("extStep")
        val result1 = extStep ?: JSONArray()
        if (result1.length() > 0) {
            return result1[0] as String
        }

        return null
    }

    /**
     * 判断ocr是否是使用三方api识别模式
     */
    fun isUseOcrApiMode(): Boolean {
        val steps: String? = mFirstNellUserFirstNellProcess?.optString("ocr_info")
        steps?.let {
            return it.equals("SDK", true)
        }
        return false
    }

    /**
     * 获取liveness待做的步骤-申请页后
     */
    fun getFirstNellNextFirstNellLivenessFirstNellAction(actionIndex: Int): String? {
        val steps: JSONArray? = mFirstNellUserFirstNellProcess?.optJSONArray("liveness_info")
        val result = steps ?: JSONArray()
        if (result.length() > actionIndex) {
            val steps0 = result[actionIndex] as String
            return steps0.lowercase() + ".json"
        }
        return null
    }
}